/**   
 * @Title: magic.java 
 * @Package com.esun 
 * @Description: MagicNumber
 * @author Miko baoz@500wan.com   
 * @date 2011-4-7 下午03:45:30  
 */
package com.esun.util.magic;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;

import com.esun.config.Config;
import com.esun.util.log.EDebug;
import com.esun.util.md5.MD5;

/**
 * @ClassName: magic
 * @Description: MagicNumber
 * @author Miko baoz@500wan.com
 * @date 2011-4-7 下午03:45:30
 * 
 */
public class magic {

	// DataBase 信息
	private static final String DBNAME = "db_arabbit2"; // 数据库名
	private static final String TABLENAME = "users"; // 表名
	private static final String TABLE_MAGIC = "magic";

	// 数据表 各列 名称定义
	private static final String NAME = "name"; // 表元素,用户名
	private static final String PWD = "password"; // ..密码
	private static final String SAVE = "save"; // ..是否保存用户信息
	private static final String ID = "_id";
	// private static final String LOGIN = "login";

	private static final String CREAT_TABLE = "CREATE TABLE " + TABLE_MAGIC + " (_id INTEGER PRIMARY KEY,magic TEXT)";

	private static Context context;

	public static void setContext(Context context) {
		magic.context = context;
	}

	private static String getNewMagicNum() {

		Random random = new Random();

		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < 10; i++) {
			int temp = random.nextInt(10);
			sb.append(temp);
		}

		String str = MD5.md5(sb.toString());

		return str;
	}

	public static String getMagicNum() {

		String magicNumber = "";

		SQLiteDatabase db = context.openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		if ((isTableExits(TABLE_MAGIC, db))) {

			Cursor cur;
			cur = db.query(TABLE_MAGIC, new String[] { "magic" }, null, null, null, null, null);

			cur.moveToFirst();

			magicNumber = cur.getString(0);
		} else {

			db.execSQL(CREAT_TABLE);
			ContentValues cv = new ContentValues();

			magicNumber = getNewMagicNum();

			cv.put(TABLE_MAGIC, magicNumber);
			db.insert(TABLE_MAGIC, null, cv);
		}

		db.close();

		return magicNumber;
	}

	public static String getPhoneRelease() {

		// String sdk = android.os.Build.VERSION.SDK; // SDK号
		// String model = android.os.Build.MODEL; // 手机型号
		String release = android.os.Build.VERSION.RELEASE; // android系统版本号

		return release;
	}

	public static String getUserName() {

		SQLiteDatabase db = context.openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		String userName = "";

		if ((isTableExits(TABLENAME, db))) {

			Cursor cur;
			cur = db.query(TABLENAME, new String[] { NAME, PWD, SAVE, ID }, null, null, null, null, null);

			cur.moveToFirst();

			userName = cur.getString(0);
		}

		db.close();

		if (userName.equals("!@#")) {
			userName = "";
		}

		EDebug.o(magic.class, "【本地用户名】" + userName);

		return userName;
	}

	public static String getScreenInfo() {

		DisplayMetrics dm;// 屏幕分辨率容器

		dm = new DisplayMetrics();

		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);

		int width = dm.widthPixels;

		int height = dm.heightPixels;

		String str = String.valueOf(width) + "x" + String.valueOf(height);

		return str;
	}

	/**
	 * 判断表是否存在
	 * 
	 * @param tablename
	 * @return true 表存在 ， false 表示不存在
	 * @author Miko
	 */
	private static boolean isTableExits(String tablename, SQLiteDatabase db) {

		boolean result = false;// 表示不存在
		String str = "SELECT COUNT(*) FROM sqlite_master where type='table' and name='" + tablename + "'";
		Cursor c = db.rawQuery(str, null);
		c.moveToFirst();
		int xcount = Integer.parseInt(c.getString(0));
		if (xcount != 0) {
			result = true; // 表存在
		}
		return result;
	}

	/**
	 * 获取入网方式方法
	 * 
	 * @return
	 */
	public static String getNetType() {

		ConnectivityManager connectManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (connectManager != null) {

			NetworkInfo netInfo = connectManager.getActiveNetworkInfo();

			if (netInfo != null) {

				int netType = netInfo.getType();

				if (netType == ConnectivityManager.TYPE_MOBILE) {

					return "mobile";

				} else {

					return "wifi";

				}

			}
		}
		// 获取不到入网方式
		return "";

	}

	public static String[] getLocationInfo(String nettype) {

		String[] info = new String[] { "", "", "" };
		EDebug.o("magic  nettype = " + nettype);
		if (nettype != null && !nettype.equals(Config.NULLMARK)) {

			// if (nettype.equals("wifi")) {
			// info = getLocationInfoWifi();
			// } else {
			info = getLocationInfoGPS();
			// }

		} else {
			info[0] = "0";
			info[1] = "0";
			info[2] = "无网络";
		}

		return info;
	}

	@SuppressWarnings("unused")
	/**获取wifi状态下的地理位置 
	 *  貌似有问题 暂时搁置*/
	private static String[] getLocationInfoWifi() {

		String[] info = new String[] { "", "", "" };

		// 获取wifi管理对象
		WifiManager mainWifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		// 判断wifi是否开启
		if (mainWifi.isWifiEnabled()) {
			// 发送接入点的扫描请求，返回true成功。否则失败
			mainWifi.startScan();
			// 启动一个线程执行第二步中的代码
		}
		BufferedReader br = null;
		try {
			// 接收请求结果，它会将所有链接wifi热点的链接信息返回
			List<ScanResult> wifiList = mainWifi.getScanResults();
			HttpPost httpRequest = new HttpPost("http://www.google.com/loc/json");
			// 封装请求的参数
			JSONObject holder = new JSONObject();
			JSONArray array = new JSONArray();
			holder.put("version", "1.1.0");
			holder.put("host", "maps.google.com");
			holder.put("request_address", true);
			for (int i = 0; i < wifiList.size(); i++) {
				// 只取当前链接信息。通过mac地址进行匹配
				// mac地址可以用macAddress = mainWifi.getConnectionInfo().getMacAddress();获得
				String macAddress = mainWifi.getConnectionInfo().getMacAddress();
				if (wifiList.get(i).BSSID.equals(macAddress)) {
					JSONObject current_data = new JSONObject();
					current_data.put("mac_address", wifiList.get(i).BSSID);
					current_data.put("ssid", wifiList.get(i).SSID);
					current_data.put("signal_strength", wifiList.get(i).level);
					array.put(current_data);
				}
			}
			holder.put("wifi_towers", array);
			StringEntity se = new StringEntity(holder.toString());
			httpRequest.setEntity(se);
			HttpResponse resp = new DefaultHttpClient().execute(httpRequest);
			if (resp.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = resp.getEntity();
				br = new BufferedReader(new InputStreamReader(entity.getContent()));
				StringBuffer sb = new StringBuffer();
				String result = br.readLine();
				while (result != null) {
					sb.append(result);
					result = br.readLine();
				}
				JSONObject location = new JSONObject(sb.toString());
				location = (JSONObject) location.get("location");
				// Location loc = new Location(LocationManager.NETWORK_PROVIDER);
				// loc.setLatitude((Double) location.get("latitude"));
				// loc.setLongitude((Double) location.get("longitude"));
				info[0] = (String) location.get("latitude");
				info[1] = (String) location.get("longitude");
				Geocoder gc = new Geocoder(context, Locale.getDefault());
				try {
					List<Address> listAddress = gc.getFromLocation((Double) location.get("latitude"), (Double) location.get("longitude"), 1);
					if (listAddress.size() > 0) {

						Address address = listAddress.get(0);

						info[2] = address.getLocality();

					}
				} catch (IOException e) {

					info[2] = "";
				}
			} else {
				info[0] = "0";
				info[1] = "0";
				info[2] = "获取失败";
			}
		} catch (Exception e) {
			info[0] = "0";
			info[1] = "0";
			info[2] = "获取失败";
		} finally {
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					// Log.e(e.toString());
				}
			}
		}

		return info;
	}

	private static String[] getLocationInfoGPS() {
		String[] info = new String[] { "", "", "" };

		Double lat = null;
		Double lng = null;
		String location = null;

		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		Location locat = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

		// 获取经纬度
		if (locat != null) {
			lat = locat.getLatitude() * 1E6 / 1E6;
			lng = locat.getLongitude() * 1E6 / 1E6;

			EDebug.o("magic lat = " + lat);
			EDebug.o("magic lng = " + lng);

			Geocoder gc = new Geocoder(context, Locale.getDefault());

			try {
				List<Address> listAddress = gc.getFromLocation(lat, lng, 1);
				if (listAddress.size() > 0) {

					Address address = listAddress.get(0);

					location = address.getLocality();
					EDebug.o("magic location = " + location);

				}
			} catch (IOException e) {

				location = "获取失败";
				EDebug.o("<异常>magic location = " + location);
			}
		} else {
			lat = 0.0;
			lng = 0.0;
			location = "";
			EDebug.o("<错误>magic location = " + location);
		}
		info[0] = lat.toString();
		info[1] = lng.toString();
		info[2] = location;
		return info;
	}

	public static String getIMEI(Context context) {

		TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		// Get deviceId
		String deviceId = telephonyManager.getDeviceId();

		if (deviceId == null) {
			deviceId = Config.NULLMARK;
		}

		return deviceId;

	}

}
